import {  logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken,getSid,setSid,removeSid } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {login} from '@/utils/httpRequet'
import ps_form from "@/api/ps_form"
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menuids:[],
  _sid:getSid(),
  userInfo:{}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_SID:(state,_sid)=>{
    state._sid = _sid
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  //可见菜单列表 
  SET_VIEWMENU:(state,menuids)=>{
    state.menuids=menuids;
  },
  setUserInfo:(state,userinfo)=>{
    if(userinfo){
      state.userInfo=userinfo;
      state.userInfo.corpId=state.userInfo? (state.userInfo.corpId||"0"):"0"
    }
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { code, password } = userInfo
    return new Promise((resolve, reject) => {
     //_APP:'hrtest'
     // login({ data:{code: code.trim(), password: CryptoJS.encryptByDES(password),_APP:ps_form.appname},url:'login',method:'post',success:response => {
        login({ data:{code: code.trim(), password: password,_APP:ps_form.appname},url:'login',method:'post',success:response => {
        if(response.errorCode<0){
          resolve(response);
          return ;
        }
        const  data  = response
        commit('SET_TOKEN', data.token)
        commit('setUserInfo', data.user)
        commit('SET_SID', data._SID)
        setToken(data.token)
        setSid(data._SID)
        resolve(response)
      },error:error => {
        reject(error)
      }
    })
    })
  },
  setUserToken({ commit }, info){
    if(info.token)
    commit('SET_TOKEN', info.token)
    if(info._SID)
    commit('SET_SID', info._SID)
    setToken(info.token)
    setSid(info._SID)
  },
  setUserInfo({commit},userInfo){
    commit("setUserInfo",userInfo)
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_ROLES', ['editor'])
      commit('SET_NAME', state.userInfo.realName)
      resolve(state.userInfo)
      //commit('SET_INTRODUCTION', introduction)
      return;
      getInfo(state.token).then(response => {
        const { data } = response
        if(!response.success){
          reject(response.msg);
        }
        if (!data) {
          reject('Verification failed, please Login again.') 
        }
        const { roles, name, avatar, introduction,menuids } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit("SET_VIEWMENU",menuids);
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(response => {
        if(response.errorCode=='1'){
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
